﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using Caliburn.Micro;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;

namespace VirtualKeyboard.UI
{
    public class AppBootstrapper : Bootstrapper<IShell>
    {
        private CompositionContainer container;
        private static Mutex appMutex;

        protected override void Configure()
        {
            container = CompositionHost.Initialize(
                new AggregateCatalog(AssemblySource.Instance.Select(x => new AssemblyCatalog(x)).OfType<ComposablePartCatalog>()));

            var batch = new CompositionBatch();

            batch.AddExportedValue<IWindowManager>(new WindowManager());
            batch.AddExportedValue<IEventAggregator>(new EventAggregator());
            batch.AddExportedValue(container);
            
            container.Compose(batch);
        }

        protected override void OnStartup(object sender, System.Windows.StartupEventArgs e)
        {
            if (IsOneProcess())
            {
                base.OnStartup(sender, e);
            }
        }

        private bool IsOneProcess()
        {
            bool createNew;
            appMutex = new Mutex(false, "VirtualKeyboardUI", out createNew);
            if (!createNew)
            {
                MessageBox.Show("只能运行一个接收器!", "提示", MessageBoxButton.OK, MessageBoxImage.Stop);
                Application.Shutdown();
                return false;
            }
            return true;
        }

        protected override object GetInstance(Type serviceType, string key)
        {
            string contract = string.IsNullOrEmpty(key) ? AttributedModelServices.GetContractName(serviceType) : key;
            var exports = container.GetExportedValues<object>(contract);

            if (exports.Count() > 0)
                return exports.First();

            throw new Exception(string.Format("Could not locate any instances of contract {0}.", contract));
        }

        protected override IEnumerable<object> GetAllInstances(Type serviceType)
        {
            return container.GetExportedValues<object>(AttributedModelServices.GetContractName(serviceType));
        }

        protected override void BuildUp(object instance)
        {
            container.SatisfyImportsOnce(instance);
        }
    }
}
